package Concurrency4_GeekTime.Chapter23_Future;

import java.util.concurrent.*;

/**
 * 功能说明：案例基础1 - 线程池
 * 开发人员：@author MaLi
 */
public class Base01_ThreadPoolExecutor {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        executor.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("通过executor提交一个任务");
            }
        });

        Future<?> future1 = executor.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("通过submit提交一个runnable任务");
            }
        });
        try {
            System.out.println(" future1 -----> "+future1.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        Future<String> future2 = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("通过submit提交一个callable任务");
                return "OK";
            }
        });

        try {
            System.out.println(" future2 -----> "+future2.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        Result result = new Result("outter");
        MyRunnable myRunnable = new MyRunnable(result);
        Future<Result> future3 = executor.submit(myRunnable, result);
        try {
            System.out.println(" future3 -----> "+future3.get());
            System.out.println("result:"+result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        executor.shutdown();
    }


    public static class Result{
        private String content;

        public Result(String content) {
            this.content = content;
        }

        @Override
        public String toString() {
            return "Result{" +
                    "content='" + content + '\'' +
                    '}';
        }
    }

    public static class MyRunnable implements Runnable{
        private Result result;

        public MyRunnable(Result result) {
            this.result = result;
        }

        @Override
        public void run() {
            result.content = "myrunnable";
        }
    }
}
